package utils

import (
	"fmt"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	"image/png"
	_ "image/png"
	"math"
	"os"

	log "gitee.com/sansaniot/ssiot-core/logger"
	"github.com/nfnt/resize"
)

const defaultWidth float64 = 320
const defaultHeight float64 = 240

type ThumbnailSize struct {
	SrcWidth  float64
	SrcHeight float64
	DesWidth  float64
	DesHeight float64
}

// 计算图片缩放后的尺寸
func _calculateRatioFit(size ThumbnailSize) (int, int) {
	ratio := math.Min(size.DesWidth/size.SrcWidth, size.DesHeight/size.SrcHeight)
	return int(math.Ceil(size.SrcWidth) * ratio), int(math.Ceil(size.SrcHeight) * ratio)
}

// 生成缩略图
func ImgThumbnail(imagePath, savePath string, width, height float64) (ThumbnailSize, error) {
	imgSize := ThumbnailSize{DesWidth: width, DesHeight: height}

	file, _ := os.Open(imagePath)
	defer file.Close()

	img, _, err := image.Decode(file)
	if err != nil {
		log.Error("提取图片大小失败", err)
		return imgSize, nil
	}

	b := img.Bounds()
	imgSize.SrcWidth = float64(b.Max.X)
	imgSize.SrcHeight = float64(b.Max.Y)

	w, h := _calculateRatioFit(imgSize)

	fmt.Println("width = ", imgSize.SrcWidth, " height = ", imgSize.SrcHeight)
	fmt.Println("w = ", w, " h = ", h)

	// 调用resize库进行图片缩放
	m := resize.Resize(uint(w), uint(h), img, resize.Lanczos3)

	// 需要保存的文件
	imgfile, _ := os.Create(savePath)
	defer imgfile.Close()

	// 以PNG格式保存文件
	err = png.Encode(imgfile, m)
	if err != nil {
		log.Error("转成缩略图失败", err)
		return imgSize, nil
	}
	return imgSize, nil
}
